<template>
  <div
    class="goods-list-container list-container"
    v-loading.fullscreen.lock="loading"
  >
    <!-- 引导使用 -->
    <!-- <div id="goods-list"></div> -->

    <!-- 搜索区域 -->
    <div
      ref="tableHeaderContainer"
      class="goods-list-search-group-container bg-w list-search-group-container"
      style="display: block"
    >
      <div class="task-list-header-search" style="align-items: center">
        <form class="task-flex task-ai" onsubmit="return false;">
          <div
            class="base-search-group input-with-append-search task-flex task-ai"
          >
            <el-input
              v-model="searchModel.keyword"
              :placeholder="$t('goods.placeHolder.productText')"
              class="task-with-input task-mr12"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>

              <el-button
                type="primary"
                slot="append"
                @click="
                  searchModel.pageNum = 1;
                  handleSearch();
                  trackEventHandler('search');
                "
                native-type="submit"
              >
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button type="plain-third" @click="resetParams">{{$t('common.base.reset')}}</el-button>
          </div>

          <!-- 老版本高级搜索 -->
          <div class="base-search">
            <div
              @click.self.stop="panelSearchAdvancedToggle"
              class="advanced-search-visible-btn"
            >
              <i class="iconfont icon-filter task-mr4"></i>
              {{$t('common.base.advancedSearch')}}
            </div>
          </div>
          <!-- 新版本高级搜索，由于数据不在es上先使用老版本高级搜索，上es以后再换回来 -->
          <!-- <div :class="['advanced-search-visible-btn', 'bg-w']">
            <advanced-search
              ref="advancedSearchRef"
              :fields="searchFieldInfo"
              :has-create="false"
              :has-save="false"
              @search="handleAdvancedSearch"
            />
          </div> -->
        </form>
      </div>

      <div class="task-list-header-nav">
        <div class="task-filter-item">
          <div class="task-font14 task-c7 state task-c8">{{$t('common.base.status')}}：</div>
          <div class="list list-crate">
            <div class="list-item task-flex task-ai">
              <div
                v-for="(item, index) in selectStateList"
                :key="index"
                class="task-nav-create"
                :class="{
                  'task-c2': selectState === item.value,
                  'task-padding-0': selectState === item.value,
                }"
                @click.stop="handleStateChange(item.value)"
              >
                <span class="actived" style="maring: 0 12px 8px 0; display: inline-block;">{{ item.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="task-list-header-nav" style="padding: 0 !important;" v-if="isMemberAuth">
        <div class="task-filter-item">
          <div class="task-font14 task-c7 state task-c8">{{ $t('common.base.type') }}：</div>
          <div class="list list-crate">
            <div class="list-item task-flex task-ai">
              <div
                v-for="(item, index) in selectGoodsTypeList"
                :key="index"
                class="task-nav-create"
                :class="{
                  'task-c2': goodsType === item.value,
                  'task-padding-0': goodsType === item.value,
                }"
                @click.stop="handleGoodsTypeChange(item.value)"
              >
                <span class="actived" style="maring: 0 12px 8px 0; display: inline-block;">{{ item.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="goods-list-section list-section">
      <div ref="tableDoContainer" class="operation-bar-container">
        <!-- 按钮区域 -->
        <div class="top-btn-group flex-x">
          <el-dropdown @command="handleReleased" v-if="publishPermission">
            <el-button type="primary">
              <i class="iconfont icon-add2"></i>{{$t('goods.list.commodityRelease')}}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="3" v-if="partsVersion"
                >{{$t('common.form.type.material')}}</el-dropdown-item
              >
              <el-dropdown-item command="1" v-else>{{$t('common.base.sparePart')}}</el-dropdown-item>
              <el-dropdown-item command="2">{{$t('common.fields.serviceName.displayName')}}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button
            type="plain-third"
            v-if="editedPermission"
            @click="openDialog('edit')"
          >
            <i class="iconfont icon-edit-square"></i>{{$t('common.base.bulkEdit')}}
          </el-button>

          <el-button
            type="plain-third"
            v-if="deletePermission"
            @click="handleDelete"
          >
            <i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}
          </el-button>

          <template v-if="putawayPermission">
            <el-button type="plain-third" @click="handleAdded">
              <i class="iconfont icon-long-arrow-up"></i>{{$t('goods.detail.onShelves')}}
            </el-button>

            <el-button type="plain-third" @click="handleSoldOut">
              <i class="iconfont icon-long-arrow-down"></i>{{$t('goods.detail.lowerShelf')}}
            </el-button>
          </template>
        </div>

        <!-- 更多操作区域 -->
        <div class="action-button-group flex-x bg-w">
          <el-dropdown
            trigger="click"
            v-if="exportPermission || editedPermission"
          >
            <div
              class="task-ai task-flex task-font14 task-c6 cur-point bg-w"
              @click="trackEventHandler('moreAction')"
            >
              <span class="task-mr4 task-ml4">{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <template v-if="exportPermission">
                <el-dropdown-item>
                  <div @click="handleExport(false)">{{$t('common.base.export')}}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="handleExport(true)">{{$t('common.base.exportAll')}}</div>
                </el-dropdown-item>
              </template>
              <template v-if="editedPermission">
                <el-dropdown-item>
                  <div @click="openDialog('update')">{{$t('common.base.batchUpdate')}}</div>
                </el-dropdown-item>
                <el-dropdown-item>
                  <div @click="openDialog('updatePic')">{{$t('goods.component.batchUpdateImg')}}</div>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div
              class="task-ai task-flex task-font14 task-c6 task-pointer task-width103 hoverClass"
              @click="handleOpenSelectColumn"
            >
              <span class="task-mr4 icon-color">{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-w pad-l-16 pad-r-16">
        <el-table
          v-table-style
          stripe
          :data="page.list"
          :highlight-current-row="false"
          :key="tableKey"
          :row-key="getRowKey"
          :border="true"
          @select="handleSelection"
          @select-all="handleSelection"
          @sort-change="sortChange"
          @header-dragend="headerDragend"
          class="task-list-table common-list-table bg-w bbx-normal-list-box goods-table"
          header-row-class-name="common-list-table-header taks-list-table-header"
          :height="tableContainerHeight"
          ref="multipleTable"
        >
          <template slot="empty">
            <BaseListForNoData
              v-show="!loading"
              :notice-msg="$t('common.base.noData')"
            ></BaseListForNoData>
          </template>
          <el-table-column type="selection" align="center"></el-table-column>
          <template v-for="(column, index) in columns">
            <el-table-column
              v-if="column.show"
              :key="`${column.field}_${index}`"
              :label="column.label"
              :prop="column.field"
              :width="column.width"
              :min-width="column.minWidth || '120px'"
              :sortable="column.sortable"
              :fixed="column.fixLeft || false"
              :align="column.align"
              show-overflow-tooltip
            >
              <template slot="header" slot-scope="scope">
                {{ column.label }}
                <template v-if="column.field === 'inventoryNumber'">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="$t('goods.list.inventoryNumDesc')"
                    placement="top"
                  >
                    <i
                      class="el-icon-warning-outline"
                      style="margin-left: 4px"
                    />
                  </el-tooltip>
                </template>
              </template>
              <template slot-scope="scope">
                <!-- 商品编号 -->
                <template v-if="column.field === 'commodityCode'">
                  <a
                    href=""
                    class="view-detail-btn"
                    v-if="scope.row.commodityCode"
                    @click.stop.prevent="handleOpenGoodsMenuTab(scope.row)"
                  >
                    {{ scope.row.commodityCode }}
                  </a>
                  <span class="ponit-label" v-if="scope.row.exchangeType"><el-tag>{{getTagName(scope.row.exchangeType)}}</el-tag></span>
                </template>
                <!-- 商品图片 -->
                <template v-else-if="column.field === 'attachmentList'">
                  <el-image
                    v-if="getUrl(scope.row.attachmentList)"
                    :src="getUrl(scope.row.attachmentList)"
                    class="view-image"
                    @click.stop="
                      previewImg(
                        getUrl(scope.row.attachmentList),
                        scope.row.attachmentList
                      )
                    "
                  ></el-image>
                </template>
                <!-- 商品类型 -->
                <template v-else-if="column.field === 'originType'">
                  {{ getOriginType(scope.row.originType) }}
                </template>
                <!-- 商品状态 -->
                <template v-else-if="column.field === 'putawayStatus'">
                  <div class="view-putaway-status">
                    <span
                      v-if="typeof scope.row.putawayStatus === 'number'"
                      :class="{ 'gray-state': scope.row.putawayStatus === 0 }"
                    >
                      {{ scope.row.putawayStatus === 0 ? $t('goods.component.offShelf') : $t('goods.component.onShelf') }}
                    </span>
                  </div>
                </template>
                <!-- 关联产品类型 -->
                <template v-else-if="column.field === 'productTypeList'">
                  {{ getProductTypeName(scope.row.productTypeList) }}
                </template>
                <!-- 外部购买链接 -->
                <template v-else-if="column.field === 'purchaseLink'">
                  <a
                    href=""
                    class="view-detail-btn"
                    v-if="scope.row.purchaseLink"
                    @click.stop.prevent="
                      handleOpenExternalLink(scope.row.purchaseLink)
                    "
                  >
                    {{ scope.row.purchaseLink }}
                  </a>
                </template>
                <!-- 服务方式 -->
                <template v-else-if="column.field === 'serviceType'">
                  {{ getServiceTypeName(scope.row.serviceType) }}
                </template>
                <!-- 库存 -->
                <template v-else-if="column.field === 'inventoryNumber'">
                  <div>{{ scope.row.inventoryNumber || 0 }}</div>
                </template>
                <!-- 价格 -->
                <template v-else-if="column.field === 'price'">
                  {{ getPrice(scope.row) }}
                </template>
                <!-- 运费 -->
                <template v-else-if="column.field === 'expressCost'">
                  {{ numFilter(scope.row.expressCost) }}
                </template>
                <!-- 上门服务费 -->
                <template v-else-if="column.field === 'serviceCost'">
                  {{ numFilter(scope.row.serviceCost) }}
                </template>
                <template v-else-if="column.field === 'standardDesc'">
                  {{ scope.row.hasSpecs == 1 ? $t('common.base.yes') : $t('common.base.no') }}
                </template>
                <template v-else-if="column.field === 'specsDesc'">
                  {{ scope.row.specsDesc }}
                </template>
                <template v-else-if="column.field === 'displayName'">
                  <template v-if="isOpenData">
                    <open-data type="userName" :openid="scope.row.staffId"></open-data>
                  </template>
                  <template v-else>
                    {{ scope.row.displayName }}
                  </template>
                </template>
                <template v-else>
                  {{
                    $formatFormField(column, scope.row)
                  }}
                </template>
              </template>
            </el-table-column>
          </template>
          <el-table-column fixed="right" :label="$t('common.base.operation')" min-width="120">
            <template slot-scope="scope">
              <el-dropdown class="dropdown " v-if="putawayPermission && (scope.row.putawayStatus === 0 || scope.row.putawayStatus === 1)">
                <span class="cur-point" >
                  {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="lang-select-dropdown table-min-width">
                  <el-dropdown-item v-if="scope.row.putawayStatus === 0"><div @click="handleAdded(scope.row)"> {{$t('goods.detail.onShelves')}}</div></el-dropdown-item>
                  <el-dropdown-item v-else-if="scope.row.putawayStatus === 1"><div @click="handleSoldOut(scope.row)">{{$t('goods.detail.lowerShelf')}}</div></el-dropdown-item>
                  <el-dropdown-item><div @click="handlePreview(scope.row)">{{$t('common.base.preview')}}</div></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div v-else>
                <el-button
                  @click.native.prevent="handlePreview(scope.row)"
                  type="text"
                  size="small"
                >
                  {{$t('common.base.preview')}}
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div
        ref="tableFooterContainer"
        class="table-footer bbx-normal-table-footer-10"
      >
        <div class="list-info">
          {{$t('goods.list.total')}} <span class="level-padding">{{ page.totalElements }}</span> {{$t('common.base.record')}}
          <template v-if="multipleSelection && multipleSelection.length > 0">
            {{$t('part.list.text2')}}
            <span
              class="product-selected-count"
              @click="multipleSelectionPanelShow = true"
            >
              {{ multipleSelection.length }}
            </span>{{$t('common.base.piece')}}
            <span class="product-selected-count" @click="toggleSelection()">
              {{$t('common.base.clear')}}
            </span>
          </template>
        </div>
        <el-pagination
          class="product-table-pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="page.pageSize"
          :current-page="page.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="page.totalElements"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 导出弹窗 -->
    <base-export-group
      ref="exportPanelRef"
      :alert="exportAlert"
      :columns="exportColumns"
      :build-params="buildExportParams"
      :group="true"
      :validate="checkExportCount"
      :needchoose-break="false"
      method="post"
      :action="goodsExport"
      :is-show-export-tip="isOpenData"
    />

    <!-- 商品发布弹窗 -->
    <GoodsReleasedDialog ref="goodsReleasedRef" @reloadPage="reloadPage" />
    <!-- 商品上架提示弹窗 -->
    <GoodsAddedDialog ref="goodsAddedRef" @reloadPage="reloadPage" />
    <!-- 批量编辑弹窗 -->
    <BatchEditingDialog
      ref="batchEditingRef"
      :selected-ids="selectedIds"
      :multiple-selection="multipleSelection"
      @reloadPage="reloadPage"
    />
    <!-- 批量更新弹窗 -->
    <BatchUpdateDialog
      ref="batchUpdateRef"
      :selected-ids="selectedIds"
      @reloadPage="reloadPage"
    />

    <!-- 老版本高级搜索-->
    <base-search-drawer
      :show.sync="visible"
      @reset="resetParams"
      @search="handleAdvancedSearch"
      @changeWidth="setAdvanceSearchColumn"
    >
      <base-search-panel
        ref="searchPanel"
        :column-num="columnNum"
        :fields="searchFieldInfo"
      />
    </base-search-drawer>

    <!-- 选择列弹窗 -->
    <biz-select-column
      ref="selectColumnRef"
      mode="goods"
      :sotrage-key="'goods_select_column'"
      @save="saveColumnStatus"
    />
  </div>
</template>

<script>
import _ from 'lodash';
import AuthMixin from '@src/mixins/authMixin';
import AuthUtil from '@src/util/auth';
import AuthEnum from '@model/enum/AuthEnum.ts';
import { goodsExport } from '@src/api/Export';
import { storageGet, storageSet } from '@src/util/storageV2';
import { openAccurateTab, isOpenData } from '@src/util/platform';
import { PageRoutesTypeEnum } from '@model/enum/PageRoutesEnum';
import { formatDate } from 'pub-bbx-utils';
import { safeNewDate } from '@src/util/time';
import { getRootWindow } from '@src/util/dom';
import { getOssUrl } from '@src/util/assets'
const goodsDefault = getOssUrl('/goodsDefault.png');
import AdvancedSearch from '@src/component/AdvancedSearch/index.vue';
import GoodsReleasedDialog from '@src/modules/linkc/goods/components/GoodsReleasedDialog.vue';
import GoodsAddedDialog from '@src/modules/linkc/goods/components/GoodsAddedDialog.vue';
import BatchEditingDialog from '@src/modules/linkc/goods/components/BatchEditingDialog.vue';
import BatchUpdateDialog from '@src/modules/linkc/goods/components/BatchUpdateDialog.vue';
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import Page from '@model/Page';
import { goodsFields, formatFields, otherFields } from '@src/modules/linkc/field.js';
import { defaultTableData } from '@src/util/table'
import {
  queryGoodsList,
  deleteGoods,
  updatePutawayStatus,
  checkPrice,
  getCommodityTypeList,
  checkAbilityToPay,
} from '@src/api/PortalApi.ts';

export default {
  mixins: [AuthMixin],
  components: {
    AdvancedSearch, // 新版本高级筛选
    GoodsReleasedDialog,
    GoodsAddedDialog,
    BatchEditingDialog,
    BatchUpdateDialog,
    BaseSearchDrawer, // 老版本高级筛选
    BaseSearchPanel,
  },
  data() {
    return {
      defaultTableData,
      loading: false,
      page: new Page(),
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        putawayStatus: 2, // 状态
        searchRuleCommodity: '', 
        orderDetail: {},
      },
      selectState: 2,
      selectStateList: [
        // 头部筛选列表
        { label: this.$t('common.base.all'), value: 2 },
        { label: this.$t('goods.component.onShelf'), value: 1 },
        { label: this.$t('goods.component.offShelf'), value: 0 },
      ],
      goodsType: '',
      selectGoodsTypeList: [
        // 头部筛选列表
        { label: this.$t('common.base.all'), value: '' },
        { label: this.$t('goods.list.pointsGoods'), value: 0 },
        { label: this.$t('goods.list.generalGoods'), value: 1 },
      ],
      multipleSelection: [],
      multipleSelectionPanelShow: false,
      columns: [],
      tableKey: (Math.random() * 1000) >> 2,
      tableContainerHeight: '440px',
      selectedLimit: 500,
      isOpenData,
      visible: false,
      columnNum: 1,
      goodsExport,
      goodsFields,
      advancedSearchParams: {},
      hasAbilityToPay: false,
    };
  },
  computed: {
    searchFieldInfo() {
      const searchGoodsFields = this.goodsFields.filter(v => v.isSearch);

      return formatFields(searchGoodsFields) || [];
    },
    // TODO 按钮权限控制
    getRowKey(row) {
      return row.id || '';
    },
    exportColumns() {
      const exportColumns = [...goodsFields, ...otherFields].filter(v => v.export);
      exportColumns.forEach(v => {
        v.label = v.displayName;
        v.exportAlias = v.fieldName;
      });

      let arr = [
        {
          label: this.$t('goods.detail.productInfo'),
          value: 'goodsExport',
          columns: exportColumns,
        },
      ];
      return arr;
    },
    selectedIds() {
      return this.multipleSelection.map(v => v.id) || [];
    },
    // 备件版本，灰度开启取备件3.0即物料，没有开启取备件2.0
    partsVersion() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.cloudwarehouse ?? true;
    },
    // 发布权限
    publishPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.PUBLISH_GOODS);
    },
    // 删除权限
    deletePermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.DELETE_GOODS);
    },
    // 编辑权限
    editedPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.EDIT_GOODS);
    },
    // 导出权限
    exportPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.EXPORT_GOODS);
    },
    // 上下架权限
    putawayPermission() {
      return AuthUtil.hasAuth(this.globalLoginUserAuth, AuthEnum.PUTAWAY_GOODS);
    },
    isMemberAuth() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.MEMBER_MANAGE
    },
  },
  mounted() {
    this.handleReloadPage();
    this.getTypeList();
    this.handleCheckAbilityToPay();

    let that_ = this;
    // 监听切换后需要重新计算列表高度
    window.addEventListener('message', event => {
      const { action, data } = event.data;
      if (action == 'shb.frame.activatedPage') {
        that_.$nextTick(() => {
          that_.knowTableContainerHeight();
        });
      }
    });
    this.$nextTick(() => {
      this.knowTableContainerHeight();
      window.onresize = _.debounce(() => {
        that_.knowTableContainerHeight();
      }, 500);
    });
  },
  methods: {
    getPrice(row) {
      if(row.hasSpecs == 1) return row.priceStr || ''
      return this.numFilter(row.priceType === 1 ? row.originPrice : row.price) || 0
    },
    getTagName(type) {
      if(type == 1) return this.$t('goods.list.pointsGoods')
      if(type == 2) return this.$t('goods.list.seveiceFeeGoods')
      return ''
    },
    async handleSearch() {
      try {
        this.loading = true;
        // this.multipleSelection = [];

        const params = {
          ...this.searchModel,
          ...this.advancedSearchParams,
        };
        const { code, data } = await queryGoodsList(params);

        if (code !== '200') {
          this.loading = false;
          this.page = this.$options.data.call(this).page;
          return this.$message.error(this.$t('goods.tips.queryListFailed'));
        }

        const { pageNum, list, total, pageSize } = data;
        [
          this.page['list'],
          this.page['totalElements'],
          this.page['pageNum'],
          this.page['pageSize'],
        ] = [list, total, pageNum, pageSize];

        this.loading = false;
        this.matchSelected();
      } catch (error) {
        this.loading = false;
        console.error('fetch goods list error', error);
      }
    },
    reloadPage() {
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
      this.handleSearch();
    },
    resetParams() {
      window.TDAPP.onEvent(this.$t('goods.list.resetEvent'));
      const option = this.$options.data.call(this);
      this.searchModel = option.searchModel;
      this.selectState = option.selectState;
      this.goodsType = option.goodsType;
      this.page = option.page;

      // 新版本方法
      // this.$refs.advancedSearchRef.resetField();
      // this.$refs.advancedSearchRef.search();
      this.$refs.searchPanel?.initFormVal();
      this.advancedSearchParams = {};
      this.handleSearch();
    },
    handleReloadPage() {
      this.buildColumns();

      this.handleSearch();
    },
    // 新版本高级搜索 ——> 点击搜索按钮
    // handleAdvancedSearch(searchModel) {
    //   const { systemConditions } = searchModel;
    //   const params = {};
    //   systemConditions.forEach(v => (params[v.property] = v.value));
    //   this.searchModel = { ...this.searchModel, ...params };
    //   this.handleSearch();
    // },
    // 老版本高级搜索 ——> 点击搜索按钮
    handleAdvancedSearch() {
      this.searchModel.pageNum = 1;
      // 获取高级搜索参数
      this.advancedSearchParams = this.$refs.searchPanel?.buildParams() || {};
      this.handleSearch();
    },
    panelSearchAdvancedToggle() {
      this.visible = true;
      window.TDAPP.onEvent(this.$t('goods.list.advancedSearchEvent'));
    },
    async getTypeList() {
      try {
        const { code, data } = await getCommodityTypeList();

        if (code !== '200' || !data) {
          return this.$message.error(this.$t('goods.tips.queryFailed'));
        }

        const typeOptions =
          data?.map(v => {
            return {
              text: v,
              value: v,
            };
          }) || [];

        this.goodsFields.forEach(v => {
          if (v.fieldName === 'originCategory') {
            v.setting.dataSource = typeOptions;
          }

          if (v.fieldName === 'originType') {
            if (this.partsVersion) {
              v.setting.dataSource = [
                {
                  text: this.$t('common.form.type.material'),
                  value: 3,
                },
                {
                  text: this.$t('common.label.serviceItem'),
                  value: 2,
                },
              ];
            } else {
              v.setting.dataSource = [
                {
                  text: this.$t('common.base.sparePart'),
                  value: 1,
                },
                {
                  text: this.$t('common.label.serviceItem'),
                  value: 2,
                },
              ];
            }
          }
        });
      } catch (error) {
        console.error('get goods type list error', error);
      }
    },
    handleStateChange(val) {
      this.selectState = val;
      this.searchModel.pageNum = 1;
      this.searchModel.putawayStatus = val;
      this.handleSearch();
    },
    handleGoodsTypeChange(val) {
      this.goodsType = val;
      this.searchModel.pageNum = 1;
      this.searchModel.searchRuleCommodity = val;
      this.handleSearch();
    },
    async handleCheckAbilityToPay() {
      try {
        const { code, data } = await checkAbilityToPay();

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.checkPaymentAbilityFailed'));
        }

        this.hasAbilityToPay = data;
      } catch (error) {
        console.error('handleCheckAbilityToPay error', error);
      }
    },
    async handleReleased(command) {
      if (
        !this.hasAbilityToPay &&
        !(await this.$platform.confirm(
          this.$t('goods.list.confirmText')
        ))
      )
        return;

      window.TDAPP.onEvent(this.$t('goods.list.commodityManagement1'));
      this.$refs.goodsReleasedRef.open(~~command);
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    openDialog(action) {
      if (action === 'edit') {
        window.TDAPP.onEvent(this.$t('goods.list.commodityManagement2'));
        this.$refs.batchEditingRef.open();
      }

      if (action === 'update') {
        window.TDAPP.onEvent(this.$t('goods.list.commodityManagement3'));
        this.$refs.batchUpdateRef.open(1);
      }

      if (action === 'updatePic') {
        window.TDAPP.onEvent(this.$t('goods.list.commodityManagement4'));
        this.$refs.batchUpdateRef.open(2);
      }
    },
    async handleDelete() {
      window.TDAPP.onEvent(this.$t('goods.list.commodityManagement5'));
      if (!this.multipleSelection.length) {
        return this.$platform.alert(this.$t('goods.placeHolder.delProduct'));
      }

      try {
        if (!(await this.$platform.confirm(this.$t('goods.tips.confirmTip')))) return;
        this.loading = true;

        const ids = this.multipleSelection.map(p => p.id);
        const { code, message } = await deleteGoods({ ids });
        this.loading = false;

        if (code !== '200') {
          return this.$message.error(message || this.$t('common.base.deleteFail'));
        }
        this.$message.success(this.$t('common.base.deleteSuccess'));

        this.multipleSelection = [];
        setTimeout(() => {
          this.handleSearch();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    // 商品上架
    async handleAdded(row) {
      window.TDAPP.onEvent(this.$t('goods.list.commodityManagement6'));
      if (!row.id && !this.multipleSelection.length) {
        return this.$platform.alert(this.$t('goods.limit.selectGoods'));
      }

      try {
        const ids = row?.id ? [row.id] : this.multipleSelection.map(p => p.id);
        const res = await checkPrice({ ids });
        if (res.code !== '200') {
          return this.$message.error(this.$t('goods.tips.verifyPriceFailed'));
        }
        if (res?.data?.length) {
          return this.$refs.goodsAddedRef.open(res.data, ids);
        }

        const { code } = await updatePutawayStatus({ ids, putawayStatus: 1 });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.launchFailed'));
        }

        this.multipleSelection = [];
        this.$message.success(this.$t('goods.tips.launchSuccess'));
        setTimeout(() => {
          this.handleSearch();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    // 下架商品
    async handleSoldOut(row) {
      window.TDAPP.onEvent(this.$t('goods.list.commodityManagement7'));
      if (!row.id && !this.multipleSelection.length) {
        return this.$platform.alert(this.$t('goods.placeHolder.selectLowerShelfProduct'));
      }

      try {
        if (!(await this.$platform.confirm(this.$t('goods.tips.confirmProductTip')))) return;

        const ids = row?.id ? [row.id] : this.multipleSelection.map(p => p.id);
        const { code } = await updatePutawayStatus({ ids, putawayStatus: 0 });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.lowerShelfFailed'));
        }

        this.multipleSelection = [];
        this.$message.success(this.$t('goods.tips.lowerShelfSuccess'));
        setTimeout(() => {
          this.handleSearch();
        }, 1000);
      } catch (error) {
        this.loading = false;
        console.error('error', error);
      }
    },
    // 预览商品
    handlePreview(row) {
      if (!row.id) return;

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsPreview,
        key: row.id,
        params: `id=${row.id}&name=${this.commodityName}&from=detail`,
      });
    },
    handleExport(exportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}商品数据.xlsx`;
      if (!exportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportNoChoice'));
        ids = this.selectedIds;
      }
      this.$refs.exportPanelRef.open(ids, fileName);
    },
    handleOpenGoodsMenuTab(row) {
      if (!row.id) return;

      let fromId = window.frameElement.getAttribute('id');

      openAccurateTab({
        type: PageRoutesTypeEnum.PageGoodsDetail,
        key: row.id,
        titleKey: ` - ${row.commodityName}`,
        params: `id=${row.id}`,
        fromId,
      });
    },
    handleOpenExternalLink(url) {
      if (!url) return;

      return this.$platform.openLink(url);
    },
    /**
     * @description 导出提示
     */
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },
    handleOpenSelectColumn() {
      window.TDAPP.onEvent(this.$t('goods.list.commodityManagement8'));
      this.$refs.selectColumnRef.open(this.columns);
    },
    // table method
    handleSelection(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms =>
        this.page.list.some(cs => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.maxDataCanChooseTips', {data1: this.selectedLimit}));
      }

      this.multipleSelection = tv;

      // this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(() => {
        this.knowTableContainerHeight();
      });
    },
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms =>
        this.page.list.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    // 匹配选中的列
    matchSelected() {
      if (!this.multipleSelection.length) return;

      const selected =
        this.page.list.filter(c => {
          if (this.multipleSelection.some(sc => sc.id === c.id)) {
            this.multipleSelection = this.multipleSelection.filter(
              sc => sc.id !== c.id
            );
            this.multipleSelection.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let item = undefined;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    sortChange(option) {
      try {
        const { prop, order } = option;
        if (!order) {
          this.searchModel.orderDetail = {};
          return this.handleSearch();
        }
        const sortedField =
          goodsFields.filter(sf => sf.fieldName === prop)[0] || {};

        let isSystem = 0;

        if (prop === 'createTime' || prop === 'updateTime') {
          isSystem = 1;
        } else {
          isSystem = sortedField.isSystem;
        }

        let sortModel = {
          isSystem,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          column: isSystem ? `${prop}` : prop,
        };

        if (
          prop === 'createTime' ||
          prop === 'updateTime' ||
          sortedField.formType === 'date' ||
          sortedField.formType === 'datetime'
        ) {
          sortModel.type = 'date';
        } else {
          sortModel.type = sortedField.formType;
        }

        this.searchModel.orderDetail = sortModel;

        this.handleSearch();
      } catch (e) {
        console.error('e', e);
      }
    },
    // 当拖动表头改变了列的宽度的时候会触发该事件
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    // 构建列表表头
    buildColumns() {
      const localStorageData = this.getLocalStorageData();
      let columnStatus = localStorageData.columnStatus || [];

      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});
      let fields = [...this.goodsFields, ...otherFields].sort((a, b) => a.orderId - b.orderId);
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        fields = this.buildSortFields(fields, localColumns);
      }

      this.columns = fields
        .filter(v => v.fieldName !== 'hasInventory' && v.show)
        .map(field => {
          let sortable = false;
          let minWidth = null;

          if (field.displayName.length > 4) {
            minWidth = field.displayName.length * 20;
          }

          if (
            ['inventoryNumber', 'saleNumber', 'viewNumber'].includes(
              field.fieldName
            )
          ) {
            sortable = 'custom';
            minWidth = 100;
          }

          if (field.fieldName === 'commodityCode') minWidth = 220;

          if (
            field.formType === 'datetime' ||
            [
              'updateTime',
              'createTime',
              'serviceType',
              'purchaseLink',
              'expressCost',
              'serviceCost',
              'standard',
              'productTypeList',
            ].includes(field.fieldName)
          ) {
            minWidth = 160;
          }

          if (['information', 'purchaseLink'].includes(field.fieldName)) {
            minWidth = 162;
          }

          if (field.fieldName === 'commodityName') minWidth = 120;

          return {
            ...field,
            label: field.displayName,
            field: field.fieldName,
            formType: field.formType,
            minWidth: typeof minWidth == 'number' ? minWidth : `${minWidth}px`,
            sortable,
            isSystem: field.isSystem,
          };
        })
        .map(col => {
          let show = col.show === true;
          let { width } = col;
          let localField =
            (localColumns[col.field] && localColumns[col.field].field) || null;

          let fixLeft = localField?.fixLeft || null;

          if (null != localField) {
            width =
              typeof localField.width == 'number'
                ? `${localField.width}px`
                : `${localField.width}`.indexOf('px')
                ? localField.width
                : '';
            show = localField.show !== false;
          }

          col.show = show;
          col.width = width;
          col.type = 'column';
          col['fixLeft'] = fixLeft && 'left';
          return col;
        });

      // return this.columns;
    },
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      // 存储列数据之后，如果存在列被删除的情况，可能产生空值，需要过滤，否则其他地方没做判断会报错
      return fields.filter(v => v).concat(unsortedFields);
    },
    /**
     * @description 构建导出参数
     * @return {Object} 导出参数
     */
    buildExportParams(checkedMap, ids, exportOneRow) {
      const { goodsExport } = checkedMap;
      const exportAll = !ids || !ids.length;

      const searchParams = {
        ...this.searchModel,
        ...this.advancedSearchParams,
      }
      const params = {
        checked: goodsExport.join(','),
        ids: ids.join(','),
        exportSearchModel: JSON.stringify(searchParams),
        dataTotal: exportAll
          ? this.page.totalElements
          : this.selectedIds.length,
      };

      return params;
    },
    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.page.totalElements > max
        ? this.$t('common.base.exportModal.oversizeTips', {size: '5000'})
        : null;
    },
    getLocalStorageData() {
      const dataStr = storageGet('goods_list_localStorage') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('goods_list_localStorage', JSON.stringify(data));
    },
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];

      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.tableKey = (Math.random() * 1000) >> 2;
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent(this.$t('goods.list.commodityManagement9'));
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent(this.$t('goods.list.commodityManagement10'));
        return;
      }
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight() {
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min =
          window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`);
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      // this.saveDataToStorage('pageSize', pageSize);
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    // 截取当前数据到小数点后两位
    numFilter(value) {
      if (!value) return '';

      let tempVal = parseFloat(value).toFixed(3);
      let realVal = tempVal.substring(0, tempVal.length - 1);

      return realVal;
    },
    getProductTypeName(arr) {
      if (!arr || arr.length === 0) return '';

      return arr.map(v => v.catalogName).join('，');
    },
    getServiceTypeName(value) {
      if (!value) return '';

      if (value === 1) return this.$t('goods.component.expressDelivery');
      if (value === 2) return this.$t('task.setting.taskTypeSetting.manage.industryNames.name7');

      return this.$t('goods.component.serviceMethod');
    },
    getOriginType(value) {
      if (!value) return '';

      if (value === 1) return this.$t('common.base.sparePart');
      if (value === 2) return this.$t('common.label.serviceItem');

      return this.$t('common.form.type.material');
    },
    getUrl(arr) {
      if (Array.isArray(arr) && arr[0]?.url) return arr[0].url || '';

      // return goodsDefault;
    },
    previewImg(url, urls = []) {
      if (url === '' || url === goodsDefault) return;

      if (typeof urls !== 'object') {
        urls = [];
      }

      urls?.forEach(v => {
        v.id = v.fileId;
      });

      this.$previewElementImg(url, urls);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@src/assets/scss/common-list.scss';

.goods-list-container {
  height: 100%;
  padding: 10px;
  overflow: auto;

  .goods-list-search-group-container {
    padding: 16px;
    border-radius: 3px;
    .base-search {
      background: #fff;
      border-radius: 3px;
      font-size: 14px;
      display: flex;
      justify-content: space-between;

      .goods-list-base-search-group {
        display: flex;
        justify-content: space-between;

        .el-input {
          width: 400px;
        }

        a {
          line-height: 33px;
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 31px;
        @include fontColor();
        border-color: $color-primary;
        background: #fff;
        padding: 0 13px;
        white-space: nowrap;
        &:hover {
          cursor: pointer;
        }

        i {
          font-size: 16px;
        }
      }
    }
  }

  .task-list {
    &-header {
      background: #ffffff;
      box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.06);
      border-radius: 4px;
      margin-bottom: 12px;
      border-top: none;

      &-search {
        width: 100%;
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        // padding: 16px;
        .advanced-search-visible-btn {
          // width: 98px;
          height: 32px;
          border-radius: 4px;
          font-size: 14px;
          @include fontColor();
          line-height: 32px;
          text-align: center;
          cursor: pointer;
          white-space: nowrap;
          margin-left: 0;

          i {
            font-size: 16px;
          }
        }

        .base-search-group {
          .el-input {
            width: 400px !important;
            input {
              border-radius: 4px 0 0 4px;
            }
          }
        }

        .customize-filter-view {
          margin-bottom: 16px;
        }
      }

      &-nav {
        padding-top: 16px;
        .task-filter-item {
          display: flex;
        }
        > div {
          position: relative;
          cursor: pointer;
          .state {
            padding-top: 4px;
            width: 100px;
          }
          .element-icon {
            position: absolute;
            right: 12px;
            top: 6px;
            span {
              color: rgba(0, 0, 0, 0.65);
            }
          }
          .list {
            padding-right: 50px;
            flex: 1;
            overflow: hidden;
            .list-item {
              > div {
                font-size: 13px;
                max-width: 160px;
                overflow-y: hidden;
                color: #595959;
                padding: 4px 8px;
                margin: 0 12px 8px 0;
                white-space: nowrap;
                overflow: hidden;
              }
            }
          }
        }
      }
    }
  }

  .task-list-header-search {
    form {
      justify-content: flex-end;
    }
  }

  .task-padding-0 {
    padding: 0 !important;
  }

  .goods-list-section {
    margin-top: 12px;
    padding-top: 0;

    .operation-bar-container {
      background: #fff;
      border-radius: 4px 4px 0 0;
      display: flex;
      justify-content: space-between;
      padding: 16px 16px 0;

      .el-dropdown-btn {
        padding: 0 15px;
        line-height: 31px;
        display: inline-block;
        background: $color-primary-light-9;
        color: $text-color-primary;
        outline: none;
        margin-left: 5px;
        .iconfont {
          margin-left: 5px;
          // font-size: 12px;
        }

        &:hover {
          cursor: pointer;
          color: #fff;
          background: $color-primary;
        }
      }
    }
  }

  .goods-table {
    .view-detail-btn {
      @include fontColor();
    }

    .view-image {
      width: 32px;
      height: 32px;
      cursor: pointer;
    }

    .view-putaway-status {
      span {
        display: block;
        min-width: 52px;
        height: 22px;
        line-height: 22px;
        text-align: center;
        background: #00c853;
        border-radius: 11px;
        font-size: 12px;
        color: #fff;
        padding:0 8px 0 8px;
      }

      .gray-state {
        background: #bdbdbd;
      }
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    padding: 0px 10px 10px 10px;
    background: #fff;
    border-radius: 0 0 3px 3px;

    .list-info {
      font-size: 13px;
      line-height: 32px;
      margin: 0;
      color: #767e89;

      .iconfont {
        position: relative;
        top: 1px;
      }

      .product-selected-count {
        color: $color-primary;
        padding: 0 3px;
        width: 15px;
        text-align: center;
        cursor: pointer;
        font-size: 13px;
      }
    }

    .el-pagination__jump {
      margin-left: 0;
    }
  }
}

.goods-list-container ::v-deep .el-table__header th {
  padding: 0;
  height: 40px;
}
.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
.ponit-label {
  margin-left: 5px;
}
.hoverClass:hover {
  color:$color-primary-light-6;
}
</style>
